﻿// CMakeProject1.cpp: 定义应用程序的入口点。
//
#include<iostream>
#include<stdlib.h>
#include "ArrayList.h"
using namespace std;

ArrayList* createTable(int num)
{
	ArrayList* table = (ArrayList*)malloc(sizeof(ArrayList));
	if (!table)
	{
		return NULL;
	}
	initTable(table, num);
	return table;
}

void deleteTable(ArrayList* table)
{
	if (table->data)
	{
		free(table->data);
		table->data = NULL;
	}
	table->capacity = 0;
	table->lenth = 0;
}

void initTable(ArrayList* table, int num)
{ 
	table->data = (elementype *)malloc(sizeof(elementype) * num);
	if (table->data == NULL)
	{
		cout << "init failed!" << endl;
	}
	table->capacity = num;
	table->lenth = 0;
}

void releaseTable(ArrayList* table)
{
	if (table)
	{
		deleteTable(table);
		free(table);
	}

}

static int enlarger(ArrayList* table)
{
	elementype* temp = (elementype*)malloc(sizeof(elementype) * table->capacity * 2);
	if (temp == NULL)
	{
		cout << "Enlarger failed!" << endl;
		return -1;
	}
	for (int i = 0; i < table->lenth; i++)
	{
		temp[i] = table->data[i];
	}
	table->capacity *= 2;
	free(table->data);
	table->data = temp;
	return 0;
}

void push_back(ArrayList* table, elementype val)
{
	if (table->lenth >= table->capacity && enlarger(table))//若溢出则扩容
	{
		return;
	}
	table->data[table->lenth] = val;
	++table->lenth;
}

void inser(ArrayList* table, int pos, elementype val)
{
	//判断pos有效性
	if (pos<0 || pos>table->lenth)
	{
		return;
	}
	//判断扩容
	if (table->lenth >= table->capacity && enlarger(table))//若溢出则扩容
	{
		return;
	}
	//移动元素
	for (int i = table->lenth - 1; i >= pos; i--)
	{
		table->data[i + 1] = table->data[i];
	}
	table->data[pos] = val;
	++table->lenth;
}

void showList(ArrayList* table)
{
	if (table == NULL)
	{
		return;
	}
	for (int i = 0; i < table->lenth; i++)
	{
		cout << table->data[i] << " ";
	}
	cout << endl;
}

void deleteVal(ArrayList* table, elementype e)
{
	//先找到所删元素的位置
	int pos = findVal(table, e);
	if (pos == -1)
	{
		return ;
	}
	//移动元素
	for (int i = pos + 1; i < table->lenth; i++)
	{
		table->data[i - 1] = table->data[i];
	}
	--table->lenth;
}

int findVal(ArrayList* table, elementype e)
{
	for (int i = 0; i < table->lenth; i++)
	{
		if (table->data[i] == e)
		{
			return i;
		}
	}
	return -1;
}

